<template>
  <div class="page-container-padding">
    <div class="param-bar">
      <el-select v-model="queryParam.v" filterable placeholder="全部品种">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-input
        placeholder="请输入内容"
        v-model="queryParam.kw"
        clearable
        style="margin-left: 10px;"
        @change="getVarietyIndex">
        <template #append>
          <el-button icon="el-icon-search" @click="getVarietyIndex"></el-button>
        </template>
      </el-input>
    </div>
    <div>
      <el-table border row-class-name='table-row' :data='tableList'>
        <el-table-column type="expand" label="详细" width='50'>
          <template slot-scope="props">
            <div style="margin-left:48px;">
              <el-form label-position="left" class="table-expand-form">
                <el-form-item label="平台ID"><span>{{ props.row.source_id }}</span></el-form-item>
                <el-form-item label="数据平台"><span>{{ props.row.source_plat }}</span></el-form-item>
                <el-form-item label="来源"><span>{{ props.row.raw_source }}</span></el-form-item>
                <el-form-item label="三方数据"><span>{{  props.row.three_plat }}</span></el-form-item>
                <el-form-item label="状态"><span>{{ props.row.state_text }}</span></el-form-item>
              </el-form>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="ID" prop="id" width="70px"></el-table-column>
        <el-table-column label="指标名称" prop="name_zh" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="namerow" @click="ToShowDataDialog(scope.row.id)">
              <span class="popHand">{{ scope.row.name_zh }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="频率" prop="frequency" width='50px' show-overflow-tooltip></el-table-column>
        <el-table-column label="源" prop="source_plat" width='50px' show-overflow-tooltip></el-table-column>
        <el-table-column label="源ID" prop="source_id" width="110px" show-overflow-tooltip></el-table-column>
        <el-table-column label="指标单位" prop="unit" width="90px" show-overflow-tooltip></el-table-column>
        <el-table-column label="起始日期" prop="startdate" width="100px"></el-table-column>
        <el-table-column label="结束日期" prop="enddate" width="100px"></el-table-column>
        <el-table-column label="创建时间" prop="create_time" width="140px"></el-table-column>
        <el-table-column label="更新时间" prop="refresh" width="140px"></el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        style="margin-top: 5px"
        background
        :current-page="queryParam.page"
        :page-size="queryParam.page_size"
        layout="total, prev, pager, next, jumper"
        :total="totalTableCount"
        @current-change="currentPageChanged"
      ></el-pagination>
    </div>
    <!-- 新建季度数据表弹窗-->
    <el-dialog :visible.sync="popIndexWindow" width="42%" height="70vh" top="2%">
      <div slot="title" style="font-size:18px;color:#555555;font-weight: bold;">{{ IndexWindow.name_zh }}</div>
      <div class="margin-box">
        <div class="IndexDataBox">
          <div style="font-size:15px;color:#040706;" class="margin-box">来源：{{ IndexWindow.raw_source }}&#8195;<span style="font-size:15px;color:#050807;">更新时间：{{ IndexWindow.refresh }}</span></div>
          <div class="data1-box">
            <div style="font-size:34px;font-weight: bold;" class="margin-box">{{ IndexWindow.latest_date }}</div>
            <div :style="{'--fontColor':fontColor}" class="color-box">{{ IndexWindow.increase_date }}</div>
            <div :style="{'--fontColor':fontColor}" class="color-box">{{ IndexWindow.increase_rate }}</div>
          </div>
          <div style="font-size:15px;color:#e42828;" class="margin-box"></div>
          <div class="data2-box">
            <div style="font-size:20px;color:#555555;font-weight: bold;" class="margin-box">统计</div>
            <div style="font-size:15px;color:#555555;" class="margin-box">样本数 <span class="date-right">{{ IndexWindow.sample_num }}</span></div>
            <div style="font-size:15px;color:#555555;" class="margin-box">数据区间<span class="date-right">{{ IndexWindow.min_date }}&#8197-&#8197{{ IndexWindow.max_date }}</span></div>
            <div style="font-size:15px;color:#555555;" class="margin-box">平均值<span class="date-right">{{ IndexWindow.average_date }}</span></div>
            <div style="font-size:15px;color:#555555;" class="margin-box">中位数<span class="date-right">{{ IndexWindow.middle_date }}</span></div>
            <div style="font-size:15px;color:#555555;" class="margin-box">标准差<span class="date-right">{{ IndexWindow.standard_date }}</span></div>
          </div>
          <div class="dateSelect-box">
            <el-date-picker
              v-model="data_range"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="prtRange"
              :disabled=this.banTime>
            </el-date-picker>
          </div>
          <div class="season-box">
            <span>季节性图表&#8194</span>
            <el-switch
              v-model="season_button"
              @change="switch_season"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :disabled=this.banSeason>
            </el-switch>
          </div>
          <div ref='chart' id="echarts" style="height:375px;width:750px" class="chart-box"></div> 
        </div>  
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getRuizyVariety} from '@/api/variety'
import {getEDBTables} from '@/api/edbdata/datalib'
import {getDetail} from '@/api/edbdata/datalib'
const echarts = require('echarts')

  export default {
    data() {
      return {
        options: [],
        input:'',
        SelectVariety:'',
        totalTableCount: 1,

        tableList:[],
        queryParam: {
          kw: '',
          v: '',
          page: 1,
          page_size: 50
        },

        popIndexWindow: false,
        IndexWindow:{
          name_zh:'',
          unit:'',
          raw_source:'',
          refresh:'',
          latest_date:'',
          increase_date:'',
          increase_rate:'',
          sample_num:'',
          min_date:'',
          max_date:'',
          average_date:'',
          middle_date:'',
          standard_date:''
        },
        fontColor:'',

        season_button: false,
        banTime:"",
        banSeason:"",
        data_range:[],
        date_flag:[],

        xAxis_x:[],
        new_x:[],
        tmp_x:[],
        yAxis_y:[],
        new_y:[],
        tmp_y:[],

        year:[],
        every_day:[],
        year_list_x:[],
        series_data:[],
      }
    },
    mounted() {
      this.getAllVariety()
      this.getVarietyIndex()
      this.getEveryday('2020-01-01', '2020-12-31')
    },
    methods: {
      getAllVariety(){
        getRuizyVariety({space: 'V03'}).then((res) =>{
          for(var i = 0; i < res.data.length; i++){
            this.options.push({
              value: res.data[i].variety_en,
              label: res.data[i].variety_long_name
            })
          }
        })
      },
      // 根据时间选择更改图表数据
      prtRange(){
        this.xAxis_x = this.tmp_x
        this.yAxis_y = this.tmp_y
        var everDate = new Date(this.data_range[0])
        var furDate = new Date(this.data_range[1])
        for(var i=0; i<this.xAxis_x.length;i++){
          var nowDate1 = new Date(this.xAxis_x[i])
          if(nowDate1.getTime() > everDate.getTime()){
            this.date_flag[0] = i
            break 
          }
        }
        for(var j=0; j<this.xAxis_x.length;j++){
          var nowDate2 = new Date(this.xAxis_x[j])
          if(nowDate2.getTime() > furDate.getTime()){
            this.date_flag[1] = j
            break
          }
        }
        this.new_x = this.xAxis_x
        this.new_y = this.yAxis_y
        this.xAxis_x = []
        this.yAxis_y = []
        for(var k=this.date_flag[0];k<this.date_flag[1];k++){
          this.xAxis_x.push(this.new_x[k])
          this.yAxis_y.push(this.new_y[k])
        }
        this.PrintChart()
      },
      // 求闰年每一天格式为 01-01 01-02的日期并装入every_day数组
      getEveryday(startTime, endTime){
        var allDate = new Array();
				var r = 0;
				//开始日期小于等于结束日期,并循环
				while (startTime <= endTime) {
					allDate[r] = startTime.substring(5,10);
					//获取开始日期时间戳
					var startTime_ts = new Date(startTime).getTime();
					//增加一天时间戳后的日期
					var next_date = startTime_ts + 24 * 60 * 60 * 1000;
					//拼接年月日，这里的月份会返回（0-11），所以要+1
					var next_dates_y = new Date(next_date).getFullYear() + "-";
					var next_dates_m =
						new Date(next_date).getMonth() + 1 < 10 ?
						"0" + (new Date(next_date).getMonth() + 1) + "-" :
						new Date(next_date).getMonth() + 1 + "-";
					var next_dates_d =
						new Date(next_date).getDate() < 10 ?
						"0" + new Date(next_date).getDate() :
						new Date(next_date).getDate();
					startTime = next_dates_y + next_dates_m + next_dates_d;
					//增加数组key
					r++;
				}
				this.every_day = allDate    
      },
      // 打开季节性图表时切换图表
      switch_season(){
        this.year = []
        this.series_data = []
        if(this.season_button == true){
          this.banTime = true
          var count = -1
          this.year_list_x = []
          for(var q=0;q<this.tmp_x.length;q++){
            if(q == 0 ){
              this.year_list_x.push([[this.tmp_x[q].substring(5,10),this.tmp_y[q]]])  
              this.year.push(this.tmp_x[q].substring(0,4))
              count = count + 1 
            }
            else if(q > 0 && this.tmp_x[q].substring(0,4) != this.tmp_x[q-1].substring(0,4)){
              count = count + 1
              this.year_list_x.push([[this.tmp_x[q].substring(5,10),this.tmp_y[q]]])   
              this.year.push(this.tmp_x[q].substring(0,4))
            }
            else{
              this.year_list_x[count].push([this.tmp_x[q].substring(5,10),this.tmp_y[q]])
            }
          }
          for(var z=0;z<this.year_list_x.length;z++){
            this.series_data.push({
              name:this.year[z],
              type:'line',
              data:this.year_list_x[z],
              smooth:false,
              showSymbol:true,
              lineStyle:{
                width:2
              },
              connectNulls:true
            })
          }
          this.PrintSeasonChart()
        }
        else if(this.season_button == false){
          this.banTime = false
          this.PrintChart()
        } 
      },
      // 获取各品种指标具体数据
      getVarietyIndex(){
        getEDBTables(this.queryParam).then((res) =>{
          const data = res.data
          this.tableList = data.records
          this.totalTableCount = data.total_count
          this.queryParam.page = data.current_page
        })
      },
      currentPageChanged(page){
        this.queryParam.page = page
        this.getVarietyIndex()
      },
      // 点击指标弹出对应季度数据对话框
      ToShowDataDialog(detail_id) {
        getDetail({detail_id: detail_id}).then((res) =>{
          this.IndexWindow.name_zh = res['data']["name"],
          this.IndexWindow.raw_source = res['data']["raw_source"],
          this.IndexWindow.refresh = res['data']["enddate"],
          this.IndexWindow.unit = res['data']["unit"],
          this.IndexWindow.latest_date = res['data']["latest_date"],
          this.IndexWindow.increase_date = res['data']["increase_date"],
          this.IndexWindow.increase_rate = res['data']["increase_rate"],
          this.IndexWindow.sample_num = res['data']["sample_num"],
          this.IndexWindow.min_date = res['data']["min_date"],
          this.IndexWindow.max_date = res['data']["max_date"],
          this.IndexWindow.average_date = res['data']["average_date"],
          this.IndexWindow.middle_date = res['data']["middle_date"],
          this.IndexWindow.standard_date = res['data']["standard_date"]
          if((res['data']["sample_num"]) == '暂无数据'){
            this.banSeason = true
            this.data_range = []
            this.xAxis_x = []
            this.yAxis_y = []
            this.PrintNullChart()
          }
          else{
            this.xAxis_x = res['data']["datadate"]
            this.yAxis_y = res['data']["datavalue"]
            this.data_range = [res['data']["datadate"][0], res['data']["datadate"][res['data']["datadate"].length -1]]
            this.PrintChart()
            this.tmp_x = this.xAxis_x
            this.tmp_y = this.yAxis_y
          }  
          this.checkColor() 
        })
        this.banTime = false
        this.banSeason = false
        this.season_button = false 
        this.popIndexWindow = true
        this.popIndexWindow = true
      },
      // 判断增量和增长率的正负赋予红绿颜色
      checkColor(){
        if(this.IndexWindow.increase_date > 0){
          this.fontColor = "#f7001a"
          this.IndexWindow.increase_date = "+" + this.IndexWindow.increase_date.toString()
          this.IndexWindow.increase_rate = "+" + this.IndexWindow.increase_rate.toString()
        }
        else if(this.IndexWindow.increase_date <= 0){
          this.fontColor = "#38b48b"
        }
        else if(this.IndexWindow.increase_date == '暂无数据'){
          this.fontColor = "#555555"
        }
      },
      // 打印"暂无数据"时的表格
      PrintNullChart(){   
        let myChart = echarts.getInstanceByDom(this.$refs.chart)  //判断DOM是否为空 如果为空则不进行渲染
        if(myChart == null){
            myChart = echarts.init(this.$refs.chart)
        }
        const tmp = this.every_day
        this.every_day = []
        myChart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer:{
                type: 'cross'
              }
            },
            graphic:{ 
              type:"text",
              left:"center",
              top:"40%",
              style:{
                  text:"暂无数据",
                  textAlign:"center",
                  fontSize:30,
                  fontWeight:10
              }
            },
            title:[
              {
                text: this.IndexWindow.name_zh,
                left:'center',
                top:'5%',
                textStyle:{
                  fontSize:15
                },
              },
            ],
            grid:{
              bottom:'19%'
            },
            xAxis: {
              type: 'category',
              scale:true,
              data: this.every_day,
              axisTick:{
                show: false
              },
            },
            yAxis: {
              type: 'value',
              min: this.IndexWindow.min_date,
              position: "left",
              scale: true,
            },  
            series:this.series_data
          }, true)
          this.every_day = tmp
      },
      //根据所获得的数据画图表(季节性表格)
      PrintSeasonChart(){   
        let myChart = echarts.getInstanceByDom(this.$refs.chart)  //判断DOM是否为空 如果为空则不进行渲染
        if(myChart == null){
            myChart = echarts.init(this.$refs.chart)
        }
        myChart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer:{
                type: 'cross'
              }
            },
            title:[
              {
                text: this.IndexWindow.name_zh,
                left:'center',
                top:'5%',
                textStyle:{
                  fontSizy:10
                },
              },
              {
                subtext: this.IndexWindow.unit,
                left:70,
                top: 20
              },
            ],
            legend:{
              show: true,
              bottom:25
            },
            dataZoom:{
              id:'dataZoomX',
              type: 'slider',
              xAxisIndex: [0],
              filterMode: 'filter',
              bottom:'1%',
              moveHandleSize: 1,
              height:"22px"
            },
            grid:{
              bottom:'19%'
            },
            xAxis: {
              type: 'category',
              scale:true,
              data: this.every_day,
              axisTick:{
                show: false
              },
            },
            yAxis: {
              type: 'value',
              min: this.IndexWindow.min_date,
              position: "left",
              scale: true,
            },  
            series:this.series_data
          }, true)
      },
      //根据所获得的数据画图表(非季节性表格)
      PrintChart(){   
        let myChart = echarts.getInstanceByDom(this.$refs.chart)  //判断DOM是否为空 如果为空则不进行渲染
        if(myChart == null){
            myChart = echarts.init(this.$refs.chart)
        }
        myChart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer:{
                type: 'cross'
              }
            },
            title:[
              {
                text: this.IndexWindow.name_zh,
                left:'center',
                top:'5%',
                textStyle:{
                  fontSizy:10
                },
              },
              {
                subtext: this.IndexWindow.unit,
                left:70,
                top: 20
              },
            ],
            dataZoom:{
              id:'dataZoomX',
              type: 'slider',
              xAxisIndex: [0],
              filterMode: 'filter',
              moveHandleSize: 0.1,
              height:"22px"
            },
            grid:{
              bottom:'20%'
            },
            xAxis: {
              type: 'category',
              data: this.xAxis_x,
              axisTick:{
                show: false
              },
            },
            yAxis: {
              type: 'value',
              min: this.IndexWindow.min_date ,
              position: "left",
              scale: true,
            },
            series:[{
              type:'line',
              data: this.yAxis_y,
              smooth: false,
              showSymbol: false,
              lineStyle:{
                width: 2.5,
              }
            }]
          }, true)
      },

    },
  }
</script>
<style scoped lang="scss">
  .param-bar {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  .popHand{
    cursor: pointer;
  }
  .margin-box{
    margin:10px;
  }
  .color-box{
    margin:10px;
    color: var(--fontColor);
    font-size: 24px;
    font-weight: bold;
  }
  .IndexDataBox{
    height: 700px;
    max-height: 80vh;
    overflow: auto;
  }
  .data1-box{
    float: left;
    background-color: #f0f0fc;
    width: 375px;
    height: 200px;
  }
  .data2-box{
    float: right;
    background-color: #f0f0fc;
    width: 375px;
    height: 200px;
  }
  .date-right{
    float: right;
  }
  .dateSelect-box{
    float: left;
    padding-top: 15px;
  }
  .season-box{
    float: right;
    padding-top: 15px;
    padding-right: 25px;
  }
  .chart-box{
    transform: translate(20px,250px);
  }
</style>
